// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 阿里云文生图API基础URL
const DASHSCOPE_BASE_URL = 'https://dashscope.aliyuncs.com/api/v1'

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { name, data } = event

    // 获取环境变量中的API-KEY
    const apiKey = process.env.DASHSCOPE_API_KEY

    if (!apiKey) {
      return {
        success: false,
        message: 'API密钥未配置，请在云函数配置中添加环境变量DASHSCOPE_API_KEY'
      }
    }

    // 根据name选择不同的操作
    switch (name) {
      case 'createImageTask':
        return await createImageTask(apiKey, data)
      case 'getImageResult':
        return await getImageResult(apiKey, data)
      default:
        return {
          success: false,
          message: '未知操作类型'
        }
    }
  } catch (error) {
    console.error('云函数执行错误:', error)
    return {
      success: false,
      message: '云函数执行错误: ' + error.message
    }
  }
}

/**
 * 创建图片生成任务
 * @param {string} apiKey - 阿里云API密钥
 * @param {object} data - 请求参数，包含prompt等信息
 */
async function createImageTask (apiKey, data) {
  try {
    const { prompt, negativePrompt, style, size, n, seed, refImg, refStrength, refMode } = data || {}

    if (!prompt) {
      return {
        success: false,
        message: '提示词不能为空'
      }
    }

    // 构建请求体
    const requestBody = {
      model: 'wanx-v1',
      input: {
        prompt: prompt
      },
      parameters: {
        style: style || '<auto>',
        size: size || '1024*1024',
        n: n || 1
      }
    }

    // 添加可选参数
    if (negativePrompt) {
      requestBody.input.negative_prompt = negativePrompt
    }

    if (refImg) {
      requestBody.input.ref_img = refImg
    }

    if (seed !== undefined && seed !== null) {
      requestBody.parameters.seed = seed
    }

    if (refStrength !== undefined && refStrength !== null) {
      requestBody.parameters.ref_strength = refStrength
    }

    if (refMode) {
      requestBody.parameters.ref_mode = refMode
    }

    // 发送创建任务请求
    const response = await axios({
      method: 'post',
      url: `${DASHSCOPE_BASE_URL}/services/aigc/text2image/image-synthesis`,
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        'X-DashScope-Async': 'enable'
      },
      data: requestBody
    })

    console.log('创建任务响应:', response.data)

    return {
      success: true,
      data: response.data
    }
  } catch (error) {
    console.error('创建图片任务错误:', error)
    let errorMessage = error.message
    if (error.response && error.response.data) {
      errorMessage = `${error.response.data.code || 'ERROR'}: ${error.response.data.message || error.message}`
    }
    return {
      success: false,
      message: errorMessage
    }
  }
}

/**
 * 查询图片生成任务结果
 * @param {string} apiKey - 阿里云API密钥
 * @param {object} data - 请求参数，包含taskId
 */
async function getImageResult (apiKey, data) {
  try {
    const { taskId } = data || {}

    if (!taskId) {
      return {
        success: false,
        message: '任务ID不能为空'
      }
    }

    // 发送查询任务请求
    const response = await axios({
      method: 'get',
      url: `${DASHSCOPE_BASE_URL}/tasks/${taskId}`,
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    })

    console.log('查询任务响应:', response.data)

    return {
      success: true,
      data: response.data
    }
  } catch (error) {
    console.error('查询任务结果错误:', error)
    let errorMessage = error.message
    if (error.response && error.response.data) {
      errorMessage = `${error.response.data.code || 'ERROR'}: ${error.response.data.message || error.message}`
    }
    return {
      success: false,
      message: errorMessage
    }
  }
} 